#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from mod_python import util,apache,Session
import uuid
import shutil
import string

import sys
reload(sys)
sys.setdefaultencoding('utf8')

__dir__         = os.path.dirname(__file__)


def __store_file( fileDesc , id):
	# Temporary store file in filesystem
	num = find_available('tmp/' + id)
	f = open( os.path.join(__dir__, 'tmp/' + id + '/' + str(num)), 'w' )
	f.write( fileDesc.value)
	f.close()


def upload(req, files):
	req.content_type = 'text/html'
	sess=Session.Session(req)
	user_id = 1000
	if sess.has_key('user_id'):
		user_id = str(sess['user_id'])
	


	# got one file
	if isinstance( files, util.Field ):
		__store_file( files , user_id)
	# got more files
	elif isinstance( files, list ):
		body = ''
		for f in files:
			__store_file( f , user_id)
	util.redirect(req, "/index.py")

def find_available(dir_name):
	max_file = 0
	for file in os.listdir(os.path.join(__dir__, dir_name)):
		if not os.path.isdir(file):
			try:
	 			name_num = string.atoi(os.path.basename(file))	
				if name_num > max_file:
					max_file = name_num
			except:
				continue
	return max_file + 1
